package com.atguigu.gmall.activity.service.impl;

import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.activity.util.CacheHelper;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.OrderRecode;
import com.atguigu.gmall.model.activity.SeckillGoods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class SeckillGoodsServiceImpl implements SeckillGoodsService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<SeckillGoods> findAll() {
        List<SeckillGoods> list = redisTemplate.opsForHash().values(RedisConst.SECKILL_GOODS);
        return list;
    }

    @Override
    public SeckillGoods getSeckillGoods(Long skuId) {
        SeckillGoods seckillGoods = (SeckillGoods) redisTemplate.opsForHash().get(RedisConst.SECKILL_GOODS, skuId.toString());
        return seckillGoods;
    }

    @Override
    public void seckillOrder(Long skuId, String userId) {
        String state = (String) CacheHelper.get(skuId.toString());
        //1、判断状态位
        if("0".equals(state)){
            //说明已售罄
            return;
        }
        //2、判断用户是否下过单
        Boolean result = redisTemplate.opsForValue().setIfAbsent(RedisConst.SECKILL_ORDERS_USERS + userId, userId, RedisConst.SECKILL__TIMEOUT, TimeUnit.SECONDS);
        if(!result){
            return;
        }
        //3、获取库存队列中的数量，如果为null，说明商品售罄，更新状态位，通知兄弟节点
        String stock = (String) redisTemplate.opsForList().rightPop(RedisConst.SECKILL_STOCK_PREFIX + skuId);
        if(StringUtils.isEmpty(stock)){
            //说明商品已售罄，更新状态位
            redisTemplate.convertAndSend("seckillpush",skuId+":0");
        }
        //4、将订单放入缓存，说明用户有下单资格，秒杀成功
        OrderRecode orderRecode = new OrderRecode();
        orderRecode.setUserId(userId);
        orderRecode.setNum(1);
        //订单码 MD5.encrypt(userId+skuId)
        orderRecode.setOrderStr(MD5.encrypt(userId+skuId));
        orderRecode.setSeckillGoods(this.getSeckillGoods(skuId));
        //将订单放入缓存
        redisTemplate.opsForHash().put(RedisConst.SECKILL_ORDERS,userId,orderRecode);

        //5、更新库存
        this.updateStockCount(skuId);

    }

    //更新库存数量
    private void updateStockCount(Long skuId) {
    }
}
